//
//  DailyReminderSheetView.m
//  FruitHelper
//
//  Created by 赵隆杰 on 2021/12/11.
//

#import "DailyReminderSheetView.h"
#import <UserNotifications/UserNotifications.h>

@interface DailyReminderSheetView ()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) UISwitch *switch_;
@property (nonatomic, copy) NSString *hourStr;
@property (nonatomic, copy) NSString *minuteStr;

@end

@implementation DailyReminderSheetView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.textColor = kColor666666;
        titleLabel.text = @"设置每日提醒";
        [self.contentView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@20);
            make.top.equalTo(self.contentView).offset(30);
            make.height.equalTo(@40);
        }];
        
        UISwitch *switch_ = [[UISwitch alloc] init];
        [switch_ addTarget:self action:@selector(switchClick:) forControlEvents:UIControlEventValueChanged];
        [self.contentView addSubview:switch_];
        [switch_ mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(titleLabel);
            make.right.equalTo(self.contentView).offset(-20);
        }];
        self.switch_ = switch_;
        
        UIPickerView *pickView = [[UIPickerView alloc] init];
        pickView.dataSource = self;
        pickView.delegate = self;
        [self.contentView addSubview:pickView];
        [pickView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.contentView);
            make.top.equalTo(titleLabel.mas_bottom).offset(0);
            make.height.equalTo(@200);
        }];
        
        UIButton *addButton = [[UIButton alloc] init];
        addButton.layer.cornerRadius = 25;
        addButton.layer.masksToBounds = YES;
        addButton.backgroundColor = kThemeColor;
        addButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [addButton setTitle:@"确定" forState:UIControlStateNormal];
        [addButton addTarget:self action:@selector(confirmBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:addButton];
        [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@50);
            make.height.equalTo(@50);
            make.centerX.equalTo(self);
            make.top.equalTo(pickView.mas_bottom).offset(30);
        }];
        
        NSString *timeStr = [LocalData getDailyReminder];
        if ([timeStr containsString:@":"]) {
            switch_.on = YES;
            NSArray *array = [timeStr componentsSeparatedByString:@":"];
            NSString *hour = array[0];
            NSString *minute = array[1];
            [pickView selectRow:[hour intValue] inComponent:0 animated:NO];
            [pickView selectRow:[minute intValue] inComponent:1 animated:NO];
            self.hourStr = hour;
            self.minuteStr = minute;
        } else {
            switch_.on = NO;
            self.hourStr = @"00";
            self.minuteStr = @"00";
        }
        
    }
    return self;
}

// 返回多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

// 返回每列的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return 24;
    }
    return 60;
}
  
// 返回pickerView 每行的内容
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component __TVOS_PROHIBITED
{
    NSString *string = nil;
    if (row < 9) {
        string = [NSString stringWithFormat:@"0%ld", row];
    } else {
        string = [NSString stringWithFormat:@"%ld", row];
    }
    if (component == 0) {
        string = [NSString stringWithFormat:@"%@时", string];
    } else {
        string = [NSString stringWithFormat:@"%@分", string];
    }
    return string;
}

// 选中行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component __TVOS_PROHIBITED
{
    if (component == 0) {
        self.hourStr = [self string2:row];
    } else {
        self.minuteStr = [self string2:row];
    }
}
    

- (void)confirmBtnClick
{
    [self dismissView];
    
    if (self.switch_.on) {
        NSString *timeStr = [NSString stringWithFormat:@"%@:%@", self.hourStr, self.minuteStr];
        [LocalData saveDailyReminder:timeStr];
        [self addLocalNotice];
        [kAppWindow makeToast:@"已设置每日提醒！" duration:2 position:CSToastPositionTop];
    } else {
        [LocalData deleteDailyReminder];
        [self deleteLocalNotice];
        [kAppWindow makeToast:@"已取消每日提醒！" duration:2 position:CSToastPositionTop];
        
    }
    
}

- (void)switchClick:(UISwitch *)st
{
    self.switch_.on = st.on;
}

- (NSString *)string2:(NSInteger)row
{
    NSString *string = nil;
    if (row < 9) {
        string = [NSString stringWithFormat:@"0%ld", row];
    } else {
        string = [NSString stringWithFormat:@"%ld", row];
    }
    return string;
}


- (void)deleteLocalNotice {
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

    [center removeAllDeliveredNotifications];
    [center removeAllPendingNotificationRequests];
}
- (void)addLocalNotice {
    
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

    //先取消已有的通知
    //直接取消全部本地通知
    [self deleteLocalNotice];
    
    UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    content.title = @"水果帮手清单";
    content.body = @"您已设置提醒，快去完成清单吧！";
    content.sound = [UNNotificationSound defaultSound];

    NSDateComponents *date = [[NSDateComponents alloc] init];
    date.hour = self.hourStr.integerValue;
    date.minute = self.minuteStr.integerValue;
    UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:date repeats:YES];
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"notification.daily" content:content trigger:trigger];

    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        NSLog(@"Error:%@", error);
    }];
    
}



@end
